/**
 * 8. String to Integer (atoi)
 * https://leetcode.com/problems/string-to-integer-atoi/
 */
package lc8;

public class Main {
  public static void main(String[] args) {
    String str = "-21474836489";
    int i = new Solution().myAtoi(str);
    System.out.println(i);
  }
}

class Solution {
  public int myAtoi(String str) {
    int n = str.length();
    if (n == 0) return 0;

    int result = 0;
    boolean f = true;
    int nagetive = 0;
    for (int i = 0; i < n; i++) {
      char c = str.charAt(i);
      if (c > 47 && c < 58) {
        if (result > (Integer.MAX_VALUE / 10)) {
          if (nagetive < 0) return Integer.MIN_VALUE;
          else return Integer.MAX_VALUE;
        }
        if (result == (Integer.MAX_VALUE / 10) && (c > (Integer.MAX_VALUE % 10 + 48))) {
          if (nagetive < 0) return Integer.MIN_VALUE;
          else return Integer.MAX_VALUE;
        }
        result = result * 10 + c - 48; // 0 -> 48  9 -> 57
        f = false;
      } else if (nagetive == 0 && f && c == ' ') {
        continue;
      } else if (f && nagetive == 0 && c == '+') {
        nagetive = 1;
      } else if (f && nagetive == 0 && c == '-') {
        nagetive = -1;
      } else {
        if (nagetive < 0) {
          result = 0 - result;
        }
        return result;
      }
    }
    if (nagetive < 0) {
      result = 0 - result;
    }
    return result;
  }
}
